# encoding: utf-8
__author__ = 'binbin'
__date__ = '2018/10/18 0013 20:26'

from rest_framework.validators import  UniqueValidator
import re
from datetime import datetime,timedelta
from Fresh_food.settings import REGEX_MOBILE
from .models import VerifyCode
from rest_framework import serializers
from django.contrib.auth import get_user_model

User = get_user_model()

class SmsSerializer(serializers.Serializer):
    mobile = serializers.CharField(max_length=11)

    def validate_mobile(self,mobile):
        '''验证手机号码'''
        # 手机号码是否已经被注册
        if User.objects.filter(mobile=mobile).count():
            raise serializers.ValidationError('用户已经存在')

        if not re.match(REGEX_MOBILE,mobile):
            raise serializers.ValidationError('手机号码非法')

        # 验证码的发送频率
        one_mintes_age = datetime.now() - timedelta(hours=0,minutes=1,seconds=0)
        if VerifyCode.objects.filter(add__time__gt=one_mintes_age,mobile=mobile).count():
            raise serializers.ValidationError('距离上一次发送未超过60s')

        return mobile


class UserDetailSerializer(serializers.ModelSerializer):
    '''用户详情'''
    class Meta:
        model = User
        fields = ('username','gender','birthday','email','mobile')


class UserRegSerializer(serializers.ModelSerializer):
    code = serializers.CharField(required=True,write_only=True,max_length=4,min_length=4,
                                 label='验证码',error_messages={
            'blank':'请输入验证码',
            'required':'请输入验证吗',
            'max_length':'验证码格式错误'
        },help_text='验证码')

    username = serializers.CharField(label='用户名',help_text='用户名',required=True,allow_blank=False
                                     ,validators=[UniqueValidator(queryset=User.objects.all(),message='用户已经存在')])

    password = serializers.CharField(label='密码',help_text='密码',write_only=True,style={'input_type':'password'})

    def validate_code(self,code):
        # 验证码在数据库是否存在，排序
        verify_records = VerifyCode.objects.filter(mobile=self.initial_data['username']).order_by('-add_time')
        if verify_records:
            last_record = verify_records[0]

            # 有效期为五分钟
            five_minter_ago = datetime.now() - timedelta(hours=0,minutes=5,seconds=0)
            if five_minter_ago > last_record.add_time:
                raise serializers.ValidationError('验证码过期')

            if last_record != code:
                raise serializers.ValidationError('验证码错误')

        else:
            raise serializers.ValidationError('验证码错误')

    def validate(self, attrs):
        attrs['mobile'] = attrs['username']
        del attrs['code']
        return attrs

    class Meta:
        model = User
        fields = ('username','code','mobile','password')

